package com.tutu.utils;

import com.tutu.core.Constant;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * json转化工具类
 * Created by sb on 14-10-17.
 */
public class WebUtil {

    static List<String> srcList;

    public static void print(HttpServletResponse response, Object data) {
        printJson(response, data);
    }

    public static void printJson(HttpServletResponse response, Object data) {
        try {
            // 设置响应头
            response.setContentType("application/json"); // 指定内容类型为 JSON 格式
            response.setCharacterEncoding(Constant.ENCODING); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtil.obj2Json(data)); // 转为 JSON 字符串
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void printJson(HttpServletResponse response, String data) {
        try {
            // 设置响应头
            response.setContentType("application/json"); // 指定内容类型为 JSON 格式
            response.setCharacterEncoding(Constant.ENCODING); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();
            writer.write(data); // 转为 JSON 字符串
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void printApi(HttpServletResponse response, Object data) {
        try {
            // 设置响应头
            response.setContentType("application/json"); // 指定内容类型为 JSON 格式
            response.setCharacterEncoding(Constant.ENCODING); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtil.obj2ApiJson(data)); // 转为 JSON 字符串
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void printApi(HttpServletResponse response, String data) {
        try {
            // 设置响应头
            response.setContentType("application/json"); // 指定内容类型为 JSON 格式
            response.setCharacterEncoding(Constant.ENCODING); // 防止中文乱码
            // 向响应中写入数据
            PrintWriter writer = response.getWriter();

            writer.write(JsonUtil.filterJson(data)); // 转为 JSON 字符串
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 调用接口 post
     */
    public static String doGetPost(String apiPath, String type, Map<String, Object> paramMap) {
        OutputStreamWriter out;
        InputStream is = null;
        String result = null;
        try {
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            if (type.equals("POST")) {
                out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); // utf-8编码
                out.append(JsonUtil.obj2Json(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            int length = connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, StandardCharsets.UTF_8); // utf-8编码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert is != null;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 从html中提取纯文本
     */
    public static String getText(String strHtml) {
        if (BaseUtil.isBlank(strHtml)) {
            return "";
        }
        String content = strHtml.replaceAll("</?[^>]+>", ""); // 剔出<html>的标签
        return content.replaceAll("<a>\\s*|\t|\r|\n</a>", "");// 去除字符串中的空格,回车,换行符,制表符
    }

    /**
     * 文本内容特殊字符转换
     */
    public static String changeText(String html, boolean flag) {
        if (flag) {
            // 数据存入
            html = html.replace("<", "&lt").replace(">", "&gt");
        } else {
            // 网页展示
            html = html.replace("&lt", "<").replace("&gt", ">");
        }

        return html;
    }

    /**
     * 从HTML中提取图片链接
     */
    public static List<String> getImgUrl(String content) {
        srcList = new ArrayList<>(); // 用来存储获取到的链接地址

        if (BaseUtil.isBlank(content)) {
            return srcList;
        }
        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");// 匹配字符串中的img标签
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        // 判断是否含有图片
        if (hasPic) {
            // 如果含有图片，那么持续进行查找，直到匹配不到
            while (hasPic) {
                String group = matcher.group(2);// 获取第二个分组的内容，也就是 (.*?)匹配到的
                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");// 匹配图片的地址
                Matcher matcher2 = srcText.matcher(group);
                // 把获取到的图片地址添加到列表中
                if (matcher2.find()) srcList.add(matcher2.group(3));

                // 判断是否还有img标签
                hasPic = matcher.find();
            }

        }
        return srcList;
    }

    /**
     * 从HTML中提取视频链接
     */
    public static List<String> getVideoUrl(String content) {
        srcList = new ArrayList<>(); // 用来存储获取到的链接地址

        if (BaseUtil.isBlank(content)) {
            return srcList;
        }
        Pattern p = Pattern.compile("<(video|VIDEO)(.*?)(>|></video>|/>)");// 匹配字符串中的video标签
        Matcher matcher = p.matcher(content);
        boolean hasPic = matcher.find();
        // 判断是否含有视频
        if (hasPic) {
            // 如果含有视频，那么持续进行查找，直到匹配不到
            while (hasPic) {
                String group = matcher.group(2);// 获取第二个分组的内容，也就是 (.*?)匹配到的
                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");// 匹配视频的地址
                Matcher matcher2 = srcText.matcher(group);
                // 把获取到的视频地址添加到列表中
                if (matcher2.find()) srcList.add(matcher2.group(3));

                // 判断是否还有img标签
                hasPic = matcher.find();
            }

        }
        return srcList;
    }

    /**
     * 获取登录的管理员信息
     */
    public static Integer getSysInfo(HttpServletRequest request, String key) {
        Object o = request.getSession().getAttribute(key);

        if (null == o || BaseUtil.isBlank(o + "")) {
            return null;
        } else {
            return Integer.parseInt(o + "");
        }
    }
}
